package com.lizk.tools.base;

/**
 * @author lizhikui
 * @date 2020/9/24 9:40
 */
public class SpeedStat {

    private static ThreadLocal<Speed>  cache = new ThreadLocal<>();

    public static void begin(){
        begin(16);
    }

    public static void begin(int length){
        Speed speed = new Speed(length);
        cache.set(speed);
        cache.get().keep();
    }

    public static void keep(){
        cache.get().keep();
    }

    public static long end(){
        cache.get().keep();
        return cache.get().end();
    }

    public static long endMillis(){
        cache.get().keep();
        return cache.get().endMillis();
    }


    static class Speed{
        long [] times;
        int size = 0;

        Speed(int size){
            times = new long[size];
        }

        public void keep(){
            this.times[size++] = System.nanoTime();
        }

        public long end(){
            boolean isMillis = false;
            printTimeList(isMillis);
            return calcTimeDiff(times[size - 1],times[0],isMillis);
        }
        public long endMillis(){
            keep();
            boolean isMillis = true;
            printTimeList(isMillis);
            return calcTimeDiff(times[size - 1],times[0],isMillis);
        }

        private void printTimeList(boolean isMillis) {
            for (int i = 0; i < size-1; i++) {
                System.out.println(calcTimeDiff(times[i + 1],times[i],isMillis));
            }
        }

        private long calcTimeDiff(long one ,long anther,boolean isMillis){
            if(isMillis){
                return (one - anther) / 1000000;
            }else{
                return (one - anther);
            }
        }
        private long calcTimeDiff(long one ,long anther){
            return calcTimeDiff(one,anther,false);
        }
    }

}
